package com.relife.sys.controller;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.relife.common.http.HttpUtil;
import com.relife.common.model.Client;
import com.relife.common.model.ClientManager;
import com.relife.common.utils.StringUtil;
import com.relife.core.entity.PermissionEntity;
import com.relife.core.qbc.QbcQuery;
import com.relife.core.service.BaseService;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;



@Controller
public class BaseController extends ModelAndView {

	public static Logger log = Logger.getLogger("Controller");
	@Autowired
	protected BaseService service;

	/**
	 * 写出消息到页
	 */
	public void write(Object message, HttpServletResponse res) {
		try {
			res.setContentType("text/html");
			res.getWriter().println(message);
			res.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 数据权限
	 * 
	 * @author WU
	 * @date 2016年4月4日 下午2:37:41
	 * @param qbc
	 */
	public void openPermission(QbcQuery qbc) {
		Client client = ClientManager.getInstance().getClientSession();
		Map<String, String> map = getdepCodeMap(client);
		if (map.size() > 0 && !client.getUser().isAdmin()) {
			List<Criterion> list = new ArrayList<Criterion>();
			for (String depCode : map.keySet()) {
				String value = map.get(depCode);
				if ("userCode".equals(value)) {
					list.add(Restrictions.eq(value, depCode));
				} else {
					list.add(Restrictions.like(value, depCode));
				}
			}
			Criterion[] crits = new Criterion[map.size()];
			qbc.add(Restrictions.or(list.toArray(crits)));
			qbc.add(Restrictions.like("depCode", client.getCompany().getDepartCode() + "%"));

		}
	}

	/**
	 * 数据权限
	 * 
	 * @author WU
	 * @date 2016年4月4日 下午2:37:53
	 * @param sql
	 * @return
	 */
	public void openPermission(StringBuffer sql, String tabPix) {
		Client client = ClientManager.getInstance().getClientSession();
		Map<String, String> map = getdepCodeMap(client);
		if (map.size() > 0 && !client.getUser().isAdmin()) {
			int i = 0;
			for (String depCode : map.keySet()) {
				String value = map.get(depCode);
				if (i == 0) {
					sql.append(" and(" + tabPix + "." + value + ("userCode".equals(value) ? "=" : " like ") + "'" + depCode + "'");
				} else {
					sql.append(" or " + tabPix + "." + value + ("userCode".equals(value) ? "=" : " like ") + "'" + depCode + "'");
				}
				sql.append((map.size() - i == 1) ? ")" : "");
				i++;
			}
			sql.append(" and " + tabPix + ".depCode like '" + client.getCompany().getDepartCode() + "%'");
		}
	}

	public String openPermission(String tabPix) {
		Client client = ClientManager.getInstance().getClientSession();
		Map<String, String> map = getdepCodeMap(client);
		String where = "";
		if (map.size() > 0 && !client.getUser().isAdmin()) {
			int i = 0;
			for (String depCode : map.keySet()) {
				String value = map.get(depCode);
				if (i == 0) {
					where += " and(" + tabPix + "." + value + ("userCode".equals(value) ? "=" : " like ") + "'" + depCode + "'";
				} else {
					where += " or " + tabPix + "." + value + ("userCode".equals(value) ? "=" : " like ") + "'" + depCode + "'";
				}
				where += (map.size() - i == 1) ? ")" : "";
				i++;
			}
			where += " and " + tabPix + ".depCode like '" + client.getCompany().getDepartCode() + "%'";
		}
		return where;
	}

	/**
	 * 数据权限
	 * 
	 * @author WU
	 * @date 2016年4月4日 下午2:46:14
	 * @param sql
	 * @param param
	 */
	public void openPermission(StringBuffer sql, List<Object> param, String tabPix) {
		Client client = ClientManager.getInstance().getClientSession();
		Map<String, String> map = getdepCodeMap(client);
		if (map.size() > 0 && !client.getUser().isAdmin()) {
			int i = 0;
			for (String depCode : map.keySet()) {
				String value = map.get(depCode);
				if (i == 0) {
					sql.append(" and(" + tabPix + "." + value + ("userCode".equals(value) ? "=" : " like ") + "?");
				} else {
					sql.append(" or " + tabPix + "." + value + ("userCode".equals(value) ? "=" : " like ") + "?");
				}
				sql.append((map.size() - i == 1) ? ")" : "");
				param.add(depCode);
				i++;
			}
			sql.append(" and " + tabPix + ".depCode like ?");
			param.add(client.getCompany().getDepartCode() + "%");
		}
	}

	/**
	 * 获取用户数据权限并组装
	 * 
	 * @author WU
	 * @date 2016年4月4日 下午2:38:11
	 * @return
	 */
	private Map<String, String> getdepCodeMap(Client client) {
		Map<String, String> map = new HashMap<String, String>();
		if (client.getUser().isAdmin()) {
			return map;
		}
		String url = HttpUtil.getRequest().getServletPath().substring(1);
		String departCode = client.getDepart().getDepartCode();
		List<PermissionEntity> list = client.getPreList();
		map.put(client.getUser().getId(), "userCode");
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				departCode = MessageFormat.format(list.get(i).getDepartCode(), departCode);
				if (StringUtil.isNotEmpty(list.get(i).getUrl())) {
					if (list.get(i).getUrl().contains(url)) {
						map.put(departCode + "%", "depCode");
					} else {
						continue;
					}
				} else {
					map.put(departCode + "%", "depCode");
				}
			}
		}
		return map;
	}
}
